﻿// ***********************************************************************
// Assembly         : NIMServerApi
// Author           : Walter
// Created          : 11-15-2016
//
// Last Modified By : Walter
// Last Modified On : 11-15-2016
// ***********************************************************************
// <copyright file="NIMHttpClient.cs" company="">
//     Copyright ©  2016
// </copyright>
// <summary></summary>
// ***********************************************************************

using System;
using System.IO;
using System.Net;
using System.Text;

namespace NIMServerApi.Commons
{
    /// <summary>
    /// Class NIMHttpClient.
    /// </summary>
    public class NIMHttpClient
    {
        /// <summary>
        /// Executes the post.
        /// </summary>
        /// <param name="appKey">The application key.</param>
        /// <param name="appSecret">The application secret.</param>
        /// <param name="nonce">The nonce.</param>
        /// <param name="curTime">The current time.</param>
        /// <param name="methodUrl">The method URL.</param>
        /// <param name="postStr">The post string.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <returns>System.String.</returns>
        public static string ExecutePost(string appKey, string appSecret,string methodUrl, string postStr,string contentType="")
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(methodUrl);
            myRequest.Method = "POST";
            if (string.IsNullOrEmpty(contentType) || contentType.Length < 10)
            {
                myRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            }
            else
            {
                myRequest.ContentType = contentType;
            }
            myRequest.ReadWriteTimeout = 30 * 1000;

            string curTime = (ConvertDateTimeInt(DateTime.Now)/1000L).ToString();
            string nonce = GetNonce();

            // 设置请求的header
            myRequest.Headers.Add("AppKey",appKey);
            myRequest.Headers.Add("Nonce", nonce);
            myRequest.Headers.Add("CurTime", curTime);
            string checkSum = CheckSumBuilder.GetCheckSum(appSecret, nonce, curTime);
            myRequest.Headers.Add("CheckSum", checkSum);

            // 设置请求的参数
            byte[] data = Encoding.UTF8.GetBytes(postStr);
            myRequest.ContentLength = data.Length;
            using (Stream newStream = myRequest.GetRequestStream())
            {
                // Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();
            }
            return GetRequestResult(myRequest);
        }

        /// <summary>
        /// Gets the request result.
        /// </summary>
        /// <param name="myRequest">My request.</param>
        /// <returns>System.String.</returns>
        private static string GetRequestResult(HttpWebRequest myRequest)
        {
            HttpWebResponse myResponse = null;
            int httpStatus = 200;
            string content;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                httpStatus = (int)myResponse.StatusCode;
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

                content = reader.ReadToEnd();
            }
            catch (WebException e)
            { //异常请求
                myResponse = (HttpWebResponse)e.Response;
                httpStatus = (int)myResponse.StatusCode;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        content = reader.ReadToEnd();
                    }
                }
            }
            return content;
        }

        /// <summary>  
        /// DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time"> DateTime时间格式</param>  
        /// <returns>Unix时间戳格式</returns>  
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// Gets or sets the nonce.
        /// </summary>
        /// <value>The nonce.</value>
        public static string GetNonce()
        {
            Random random = new Random();
            return random.Next(100000, 999999).ToString();
        }
    }
}